<?php
/**
 * PaypalController.php
 *
 * @copyright  2022 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     Edward Yang <yangjin@guangda.work>
 * @created    2022-08-10 18:57:56
 * @modified   2022-08-10 18:57:56
 *
 * https://www.zongscan.com/demo333/1311.html
 * https://clickysoft.com/how-to-integrate-paypal-payment-gateway-in-laravel/
 * https://www.positronx.io/how-to-integrate-paypal-payment-gateway-in-laravel/
 */

namespace Plugin\Wooshpay\Controllers;

use Beike\Repositories\OrderPaymentRepo;
use Beike\Repositories\OrderRepo;

use Beike\Services\StateMachineService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;
use Plugin\Wooshpay\Services\WooshpayService;
class WooshpayController
{

    /**
     * 创建 paypal 订单
     * @param Request $request
     * @return JsonResponse
     * @throws \Throwable
     */
    public function create(Request $request) : JsonResponse
    {
        $data        = \json_decode($request->getContent(), true);
        $customer    = current_customer();
        $order      =   OrderRepo::getOrderByNumber($data['orderNumber'] , $customer);
        $wooshpayService   =    new WooshpayService($order);
        return response()->json($wooshpayService->createOrder($data));
    }

    /**
     * 客户同意后扣款回调
     * @param Request $request
     * @return JsonResponse
     * @throws \Throwable
     */
    public function capture(Request $request) : JsonResponse
    {
        $data        = \json_decode($request->getContent(), true);

        $customer    = current_customer();


        $order      =   OrderRepo::getOrderByNumber($data['orderNumber'] , $customer);
        $wooshpayService   =    new WooshpayService($order);

        if(isset($data['id'])){
            $data     =   $wooshpayService->confirm($data);
        }
        if ($data['status'] != 'succeeded')
        {
            $data     =   $wooshpayService->confirm($data);
        }

        OrderPaymentRepo::createOrUpdatePayment($order->id, [

                'transaction_id'    => $data['id'],
                'request'           =>  $data['status'],
                'response'          =>  $data,

        ]);

        try {
            DB::beginTransaction();
            if ($data['status'] == 'succeeded' ) {
                StateMachineService::getInstance($order)->changeStatus(StateMachineService::PAID);
                DB::commit();
            }
        } catch (\Exception $e) {
            DB::rollBack();
            dd($e);
        }

        return response()->json(['errCode'=>200 , 'message'=>'ok' , 'data'=>$data]);
//        $wooshpayService   =    new WooshpayService($order);
//
//        return response()->json($wooshpayService->confirmOrder($data));
    }


}
